package com.shanghaionstar.home.life;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.common.util.EncryptUtil;
import com.onstar.cn.common.util.PreferencesUtls;
import com.onstar.cn.framework.annotation.FindViewById;
import com.onstar.cn.framework.mvp.base.core.BaseActivity;
import com.onstar.cn.framework.mvp.base.core.BaseFragment;
import com.onstar.cn.mag.PlateEngineNumEntity;
import com.onstar.cn.mag.publicService.response.PreferentialResEntity;
import com.onstar.cn.mag.publicService.response.ResponBannerEntity;
import com.onstar.cn.weight.ProgressLayout;
import com.shanghaionstar.R;
import com.shanghaionstar.activity.webview.handler.CheYinInsuranceHandler;
import com.shanghaionstar.activity.webview.handler.CommonWebViewActivity;
import com.shanghaionstar.activity.webview.handler.IWebType;
import com.shanghaionstar.activity.webview.handler.WebDataEntity;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.home.ImageCycleView;
import com.shanghaionstar.home.iview.IAssuranceView;
import com.shanghaionstar.home.presenter.AssurancePresenter;
import com.shanghaionstar.home.util.PreferentialResFactory;
import com.shanghaionstar.user.UpdateInsuranceCompanyFragment;
import com.shanghaionstar.utils.AlertDialogUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.FinalConstants;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * Created by Rengui Lu on 2017/1/5.
 */
public class AssuranceFragment extends BaseFragment implements IAssuranceView {
    @FindViewById(R.id.cur_comp_rl)
    private RelativeLayout mCurCompRl;
    @FindViewById(R.id.ins_date_rl)
    private RelativeLayout mInsDateRl;
    @FindViewById(R.id.bus_date_rl)
    private RelativeLayout mBusDateRl;
    @FindViewById(R.id.banner_icv)
    private ImageCycleView mBannerIcv;
    @FindViewById(R.id.progress_layout)
    private ProgressLayout mProgressLayout;
    @FindViewById(R.id.order_assurance_btn)
    private Button mOrderBtn;
    @FindViewById(R.id.btn_tv)
    private TextView mBtnTv;
    @FindViewById(R.id.reminder_tv)
    private TextView mReminderTv;
    @FindViewById(R.id.web_rl)
    private RelativeLayout mWebRl;
    @FindViewById(R.id.proclaim_wv)
    private WebView mProclaimWv;

    private PayStatusDialog payStatusDialog;

    private ViewHolder mCurCompHolder;
    private ViewHolder mInsDateHolder;
    private ViewHolder mBusDateHolder;

    private AssurancePresenter mPresenter;
    private BaseActivity mActivity;

    private String businessInsuranceExpireDate;
    private String compulsoryInsuranceExpireDate;

    //车主首页传值
    private PreferentialResEntity entity;

    @Override
    public int getLayoutId() {
        return R.layout.owner_life_assurance;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mActivity = (BaseActivity) activity;
    }

    static class ViewHolder {
        private RelativeLayout rl;
        TextView titleTv;
        TextView rightTv;

        public ViewHolder(RelativeLayout rl) {
            if (rl == null)
                throw new NullPointerException("The Holder view is null");
            this.rl = rl;
            titleTv = (TextView) rl.findViewById(R.id.title_tv);
            rightTv = (TextView) rl.findViewById(R.id.right_tv);
        }
    }

    /**
     * @param url 显示协议弹窗
     */
    private void showDia(String url) {
        payStatusDialog = new PayStatusDialog(mActivity, protocolListener);
        payStatusDialog.show();
    }

    PayStatusDialog.IProtocolClickListener protocolListener = new PayStatusDialog.IProtocolClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.refuse_tv:
                    BusinessUtil.sendReportByClickType(mActivity, FunctionNameFindId.Insurance_unpayed.getStringValue());
                    payStatusDialog.dismiss();
                    back();
                    break;
                case R.id.agree_tv:
                    BusinessUtil.sendReportByClickType(mActivity, FunctionNameFindId.Insurance_payed.getStringValue());
                    payStatusDialog.dismiss();
//                    presenter.localVehicleService();
                    break;
                case R.id.close_iv:
                    BusinessUtil.sendReportByClickType(mActivity, FunctionNameFindId.Insurance_paymentback.getStringValue());
                    payStatusDialog.dismiss();
//                    presenter.localVehicleService();
                    break;
            }
        }
    };

    private void initViewHolder() {
        mProclaimWv.loadUrl(Constants.CURRENT_PREFIX_H5_URL+ Constants.INSPECTION_DISCLAIMER_SUFFIX);
        mCurCompHolder = new ViewHolder(mCurCompRl);
        mInsDateHolder = new ViewHolder(mInsDateRl);
        mBusDateHolder = new ViewHolder(mBusDateRl);
        mCurCompHolder.titleTv.setText(R.string.assurance_current_company);
        mInsDateHolder.titleTv.setText(R.string.assurance_maturity_date);
        mBusDateHolder.titleTv.setText(R.string.commercial_maturity_date);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mPresenter = new AssurancePresenter(mActivity.getScheduler());
        mPresenter.setView(this);
        entity = (PreferentialResEntity) getArguments().getSerializable("entity");
//        entity = new BannerUtil(mActivity).setCheYinEntity(entity);
        entity = PreferentialResFactory.createAssuranceEntity(entity, mActivity);
        initViewHolder();
        initListener();


        mPresenter.updateVehicleInfo("", "", "", true);
        mPresenter.start();
        mPresenter.commandData();
    }

    private void showDatePicker(final String dateString, final boolean isBusiness) {
        SimpleDateFormat sdf = new SimpleDateFormat(FinalConstants.DATE_FORMAT);
        Calendar calendar = Calendar.getInstance(Locale.CHINA);
        try {
            Date date = sdf.parse(dateString);
            calendar.setTime(date);
        } catch (Exception e) {
            e.printStackTrace();
            calendar.setTime(new Date(System.currentTimeMillis()));
        }
        DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int year, int montyOfYear, int dayOfMonth) {
                StringBuilder sb = new StringBuilder();
                sb.append(year);
                sb.append("-");
                sb.append((montyOfYear + 1) < 10 ? 0 + (montyOfYear + 1) : (montyOfYear + 1));
                sb.append("-");
                sb.append(dayOfMonth);
                if (!isBusiness) {
                    compulsoryInsuranceExpireDate = sb.toString();
                    mInsDateHolder.rightTv.setText(TextUtils.isEmpty(compulsoryInsuranceExpireDate) ? "" : compulsoryInsuranceExpireDate);
//                    PreferencesUtls.getInstance(getActivity()).put(Constants.COMPULSORY_INSURANCE_EXPIRATION_DATE,compulsoryInsuranceExpireDate);
                } else {
                    businessInsuranceExpireDate = sb.toString();
                    mBusDateHolder.rightTv.setText(TextUtils.isEmpty(businessInsuranceExpireDate) ? "" : businessInsuranceExpireDate);
//                    PreferencesUtls.getInstance(getActivity()).put(Constants.BUSINESS_INSURANCE_EXPIRATION_DATE,businessInsuranceExpireDate);
                }
                AlarmManagerUtil.notifyAssuranceExpireDate(getActivity(), sb, isBusiness);
                mPresenter.updateVehicleInfo("", isBusiness ? "" : sb.toString(), isBusiness ? sb.toString() : "", false);
                mPresenter.start();
            }
        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
        datePickerDialog.show();
    }

    private void gotoCheYin() {
//        Intent intent2 = new Intent(mActivity,CommonWebViewActivity.class);
//        Bundle bundle = new Bundle();
//        bundle.putSerializable(IWebType.KEY_SERIAL_DATA,entity);
//
//        startActivity(intent2);
        WebDataEntity mWebData = new WebDataEntity();
        mWebData.setClzName(CheYinInsuranceHandler.class.getName());
        mWebData.setWhat(IWebType.TYPE_CHE_YIN_INSURANCE);
        mWebData.setTopTitle(getString(R.string.assurance_order));
        CommonWebViewActivity.launchCommonWeb(mActivity,mWebData,entity);
    }

    private void initListener() {
        mOrderBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                mPresenter.getH5(entity);
                BusinessUtil.sendReportByClickType(mActivity, FunctionNameFindId.Insurance_Renew.getStringValue());
                gotoCheYin();
            }
        });
        mCurCompRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mActivity instanceof OwnerLifeActivity) {
                    BusinessUtil.sendReportByClickType(mActivity, FunctionNameFindId.Insurance_Insurer.getStringValue());
                    ((OwnerLifeActivity) mActivity).changeFragment(UpdateInsuranceCompanyFragment.class.getName());
                }
            }
        });
        mInsDateRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BusinessUtil.sendReportByClickType(mActivity, FunctionNameFindId.Insurance_Complusoryexpirydate.getStringValue());
                showDatePicker(compulsoryInsuranceExpireDate, false);
            }
        });
        mBusDateRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BusinessUtil.sendReportByClickType(mActivity, FunctionNameFindId.Insurace_AutoExpirydate.getStringValue());
                showDatePicker(businessInsuranceExpireDate, true);
            }
        });


        mBtnTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int vis = mWebRl.getVisibility();
                if (vis == View.GONE) {
                    BusinessUtil.sendReportByClickType(mActivity, FunctionNameFindId.Insurance_OpenDisclaimer.getStringValue());
                    mBtnTv.setText("");
                    mWebRl.setVisibility(View.VISIBLE);
                } else {
                    BusinessUtil.sendReportByClickType(mActivity, FunctionNameFindId.Insurance_CloseDisclaimer.getStringValue());
                    mBtnTv.setText(R.string.assurance_declare);
                    mWebRl.setVisibility(View.GONE);
                }
            }
        });

        mReminderTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int vis = mWebRl.getVisibility();
                if (vis == View.GONE) {
                    mBtnTv.setText("");
                    mWebRl.setVisibility(View.VISIBLE);
                } else {
                    mBtnTv.setText(R.string.assurance_declare);
                    mWebRl.setVisibility(View.GONE);
                }
            }
        });

    }

    @Override
    public void onResume() {
        super.onResume();
        String insuranceComp = PreferencesUtls.getInstance(mActivity).getString("insuranceComp", "");
        if (!TextUtils.isEmpty(insuranceComp))
            mCurCompHolder.rightTv.setText(insuranceComp);
    }

    @Override
    public void setLoading(boolean isLoading) {
        mProgressLayout.setVisibility(isLoading ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onResponseError(OnStarException e) {
        AlertDialogUtil.showDialogByOnstarException(onActivity(), e);
    }

    @Override
    public void onReponseSuccess(PlateEngineNumEntity object) {
        if (object != null) {
            businessInsuranceExpireDate = object.getBusinessInsuranceExpireDate();
            compulsoryInsuranceExpireDate = object.getCompulsoryInsuranceExpireDate();
            String insuranceComp = object.getInsuranceComp();
            if (!TextUtils.isEmpty(insuranceComp))
                mCurCompHolder.rightTv.setText(insuranceComp);
            if (!TextUtils.isEmpty(compulsoryInsuranceExpireDate))
                mInsDateHolder.rightTv.setText(compulsoryInsuranceExpireDate);
            if (!TextUtils.isEmpty(businessInsuranceExpireDate))
                mBusDateHolder.rightTv.setText(businessInsuranceExpireDate);
        }
    }


    @Override
    public Activity onActivity() {
        return getActivity();
    }

    FunctionNameFindId[] functionNameFindIds = {FunctionNameFindId.Insurance_banner1,
            FunctionNameFindId.Insurance_banner2,
            FunctionNameFindId.Insurance_banner3,
            FunctionNameFindId.Insurance_banner4,
            FunctionNameFindId.Insurance_banner5};

    @Override
    public void onGetBanner(List<ResponBannerEntity> entities) {
        if (CommonUtil.isNull(entities)) {
//           discover_banner_iv.initBanner();
        } else {
            final DisplayImageOptions options = new DisplayImageOptions.Builder().showStubImage(R.drawable.home_banner_failed)
                    .showImageForEmptyUri(R.drawable.home_banner_failed).showImageOnFail(R.drawable.home_banner_failed)
                    .resetViewBeforeLoading(true).cacheInMemory(true).cacheOnDisc(false).imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
                    .bitmapConfig(Bitmap.Config.RGB_565).displayer(new FadeInBitmapDisplayer(100)).build();
            mBannerIcv.setVisibility(View.VISIBLE);
            mBannerIcv.setImageResources(entities, new ImageCycleView.ImageCycleViewListener() {
                @Override
                public void displayImage(Object o, ImageView imageView) {
                    if (o == null || imageView == null) {
                        mBannerIcv.setVisibility(View.GONE);
                        return;
                    }
                    ResponBannerEntity entity = (ResponBannerEntity) o;
                    ImageLoader.getInstance().displayImage(entity.getImgUrl(), imageView, options);
                }

                @Override
                public void onImageClick(Object o, int position, View imageView) {
                    if (o == null || imageView == null) {
                        mBannerIcv.setVisibility(View.GONE);
                        return;
                    }
                    if (position < functionNameFindIds.length)
                        BusinessUtil.sendReportByClickType(mActivity, functionNameFindIds[position].getStringValue());
                    if(o instanceof ResponBannerEntity)
                        mPresenter.onBannerClick((ResponBannerEntity) o);
                }
            });
        }
    }
}
